//
//  BIImageBrowserViewController.m
//  iCarrouselLayout
//
//  Created by ET|冰琳 on 16/3/21.
//  Copyright © 2016年 Butterfly. All rights reserved.
//

#import "BIImageBrowserViewController.h"
#import "iCarrouselContainerView.h"
#import "BIAlertViewController.h"
#import "UIImageURLSize.h"

@interface BIImageBrowserViewController ()

@property (nonatomic, copy  ) iCarrouselCellConfiguration cellConfiguration;

@end


@implementation BIImageBrowserViewController

- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
        [self initialization];
    }
    return self;
}

- (instancetype)init{
    if (self = [super init]) {
        [self initialization];
    }
    return self;
}

- (instancetype)initWithCoder:(NSCoder *)aDecoder{
    if (self = [super initWithCoder:aDecoder]) {
        [self initialization];
    }
    return self;
}


- (UIStatusBarStyle)preferredStatusBarStyle {
    return UIStatusBarStyleLightContent;
}

- (void)initialization{
    
    self.hidesBottomBarWhenPushed = true;
    
    self.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
    
    if ([[[UIDevice currentDevice] systemVersion] floatValue]>= 8.0) {
        
        self.modalPresentationStyle = UIModalPresentationCustom;
    }else{
        self.modalPresentationStyle = UIModalPresentationCurrentContext;
    }
}

- (BIImageBrowserContainerView *)browserView{
    if (!_browserView) {
        BIImageBrowserLayout *layout = [BIImageBrowserLayout new];
        layout.itemSize = [UIScreen mainScreen].bounds.size;
        
        _browserView = [[BIImageBrowserContainerView alloc] initWithFrame:[UIScreen mainScreen].bounds
                                                     collectionViewLayout:layout];
//        __weak BIImageBrowserViewController *_weak_self = self;
//        _containerView.cellConfiguration = ^(BIImageBrowserCollectionViewCell * cell, NSIndexPath *indexPath){
//            __strong BIImageBrowserViewController *self = _weak_self;
//            cell.imageView.contentMode = UIViewContentModeCenter;
//            [cell.imageView sd_setImageWithURL:[NSURL URLWithString:self.imageArr[indexPath.section]]];
//        };
    }
    return _browserView;
}

- (void)viewDidLoad {
    [super viewDidLoad];

    // Do any additional setup after loading the view.
    [self.view setBackgroundColor:[UIColor blackColor]];
    

    [self.browserView registerCell:[BIImageBrowserCollectionViewCell class]];
    
    [self.view addSubview:self.browserView];
    
    
    UITapGestureRecognizer *doubleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(doubleTaped:)];
    doubleTap.numberOfTapsRequired = 2;
    [self.view addGestureRecognizer:doubleTap];

    UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapped:)];
    [singleTap requireGestureRecognizerToFail:doubleTap];
    [self.view addGestureRecognizer:singleTap];
    
    UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPressed:)];
    [self.view addGestureRecognizer:longPress];
    
    BIImageBrowserLayout *layout = (BIImageBrowserLayout *)self.browserView.collectionView.collectionViewLayout;
    layout.selectIndexPath = self.selectIndexPath;
    layout.sourceLayout    = self.sourceLayout;
    [self.browserView.collectionView reloadData];
    
    [self.browserView showPage:self.selectIndexPath.row animate:TRUE];
    
    
    if (self.animateTransition) {
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.01 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            
            layout.selectIndexPath = nil;
            [layout animateShowIndexPath:self.selectIndexPath destinationSize:[UIImageURLSize getImageSizeWithURL:self.browserView.dataArr[self.selectIndexPath.row]]];
            
        });
    }
    
}


#pragma mark - action
- (void)tapped:(UITapGestureRecognizer *)tap{
    
    if (self.animateTransition) {
        NSIndexPath *indexPath = [self.browserView.collectionView indexPathForItemAtPoint:[tap locationInView:self.browserView.collectionView]];
        
        if (indexPath) {
            BIImageBrowserLayout *layout = (BIImageBrowserLayout *)self.browserView.collectionView.collectionViewLayout;
            self.view.backgroundColor = [UIColor clearColor];
            [layout animateDismissIndexPath:indexPath completion:^{
                [self dismissViewControllerAnimated:YES completion:nil];
            }];
        }
    }else{
        [self dismissViewControllerAnimated:YES completion:nil];
    }
}

- (void)doubleTaped:(UITapGestureRecognizer *)tap{
    NSIndexPath *indexPath = [self.browserView.collectionView indexPathForItemAtPoint:[tap locationInView:self.browserView]];
    BIImageBrowserCollectionViewCell *cell = (BIImageBrowserCollectionViewCell *)[self.browserView.collectionView cellForItemAtIndexPath:indexPath];
    [cell animateScaleImage];
}

- (void)longPressed:(UILongPressGestureRecognizer *)press{
    if (press.state == UIGestureRecognizerStateBegan) {
        NSIndexPath *indexPath = [self.browserView.collectionView indexPathForItemAtPoint:[press locationInView:self.browserView.collectionView]];
        BIImageBrowserCollectionViewCell *cell = (BIImageBrowserCollectionViewCell *)[self.browserView.collectionView cellForItemAtIndexPath:indexPath];
        [self saveImage:cell.imageView.image];
        
        if (cell.imageView.image) {
            
            BIAlertViewController *alert = [BIAlertViewController new];
            
            BIAlertAction *saveAction = [BIAlertAction actionWithTitle:@"保存图片" action:^{
                [self saveImage:cell.imageView.image];
            }];
            
            BIAlertAction *cancel = [BIAlertAction actionWithTitle:@"取消" action:nil];
            
            /*[alert addAction:shareImageAction];*/
            [alert addAction:saveAction];
            [alert addAction:cancel];
            [self presentViewController:alert animated:true completion:nil];
        }
    }
}

- (void)saveImage:(UIImage *)image{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        UIImageWriteToSavedPhotosAlbum(image, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
    });
}

- (void)saveImageSuceed{
    //[[HUDSinglaton shareSinglaton] showHUDThenHideWithText:@"已保存至系统相册" andView:[UIApplication sharedApplication].keyWindow];
}

- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo{
    [self saveImageSuceed];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */
@end



@implementation BIImageBrowserLayout

// TODO: 按图片实际大小展示在cell中
- (void)animateShowIndexPath:(NSIndexPath *)indexPath destinationSize:(CGSize)size{
    CGRect frame = [self.sourceLayout layoutAttributesForItemAtIndexPath:indexPath].frame;
    
    CGRect originFrame = [self layoutAttributesForItemAtIndexPath:indexPath].frame;
    originFrame.origin.x = fmod(originFrame.origin.x, self.collectionView.frame.size.width);
    originFrame.origin.y = (self.collectionView.frame.size.height - size.height * size.width/ self.collectionView.frame.size.width);
    originFrame.size.height = self.collectionView.frame.size.height - originFrame.origin.y * 2;
    
    BIImageBrowserCollectionViewCell *cell = (BIImageBrowserCollectionViewCell *)[self.collectionView cellForItemAtIndexPath:indexPath];
    
    CGRect startAniFrame = [self.sourceLayout.collectionView convertRect:frame toView:self.collectionView];
    startAniFrame.origin.x = fmod(startAniFrame.origin.x, self.collectionView.frame.size.width);
    cell.imageView.frame = startAniFrame;
    
    [UIView animateWithDuration:0.3 animations:^{
        cell.imageView.frame = originFrame;
    }];
}

- (void)animateShowIndexPath:(NSIndexPath *)indexPath {
    
//    return;
//    if (indexPath.row == self.selectIndexPath.row)
    {
        //animate
        CGRect frame = [self.sourceLayout layoutAttributesForItemAtIndexPath:indexPath].frame;
        
        CGRect originFrame = [self layoutAttributesForItemAtIndexPath:indexPath].frame;
        originFrame.origin.x = fmod(originFrame.origin.x, self.collectionView.frame.size.width);
        
        BIImageBrowserCollectionViewCell *cell = (BIImageBrowserCollectionViewCell *)[self.collectionView cellForItemAtIndexPath:indexPath];
        
        CGRect startAniFrame = [self.sourceLayout.collectionView convertRect:frame toView:self.collectionView];
        startAniFrame.origin.x = fmod(startAniFrame.origin.x, self.collectionView.frame.size.width);
        cell.imageView.frame = startAniFrame;
        
        [UIView animateWithDuration:0.3 animations:^{
            cell.imageView.frame = originFrame;
        }];
    }
}

- (void)animateDismissIndexPath:(NSIndexPath *)indexPath completion:(dispatch_block_t)completion{
    
    CGRect frame = [self.sourceLayout layoutAttributesForItemAtIndexPath:indexPath].frame;
    
    CGRect originFrame = [self layoutAttributesForItemAtIndexPath:indexPath].frame;
    
    originFrame.origin.x = fmod(originFrame.origin.x, self.collectionView.frame.size.width);
    
    BIImageBrowserCollectionViewCell *cell = (BIImageBrowserCollectionViewCell *)[self.collectionView cellForItemAtIndexPath:indexPath];
    
    CGRect startAniFrame = [self.sourceLayout.collectionView convertRect:frame toView:self.collectionView];
    startAniFrame.origin.x = fmod(startAniFrame.origin.x, self.collectionView.frame.size.width);
    cell.imageView.frame = originFrame;
    
    [UIView animateWithDuration:0.3 animations:^{
        cell.imageView.frame = startAniFrame;
    } completion:^(BOOL finished) {
        if (finished) {
            completion();
        }
    }];

}


@end



@implementation BIImageBrowserContainerView



- (void)registerCollectionCells{
    [self.collectionView registerClass:[BIImageBrowserCollectionViewCell class] forCellWithReuseIdentifier:@"cell"];
}

@end


@interface BIImageBrowserCollectionViewCell ()<UIScrollViewDelegate>

@property (nonatomic, strong) UIScrollView *scaleView;

@end

@implementation BIImageBrowserCollectionViewCell

- (void)prepareForReuse{
    [super prepareForReuse];
    self.scaleView.zoomScale = 1.0;
    self.imageView.frame = self.bounds;
}

-  (instancetype)initWithFrame:(CGRect)frame{
    if (self = [super initWithFrame:frame]) {
        
        self.scaleView = [[UIScrollView alloc] initWithFrame:self.bounds];
        self.scaleView.delegate = self;
        self.scaleView.maximumZoomScale = 2.0;
        self.scaleView.showsHorizontalScrollIndicator = false;
        self.scaleView.showsVerticalScrollIndicator = false;
        
        [self.contentView addSubview:self.scaleView];
        
        self.imageView = [[UIImageView alloc] initWithFrame:self.bounds];
        [self.scaleView addSubview:self.imageView];

        self.imageView.clipsToBounds = true;
        self.imageView.contentMode = UIViewContentModeScaleAspectFit;
        
        self.indicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhite];
        self.indicator.center = CGPointMake(self.frame.size.width/2.0, self.frame.size.height/2.0);
        [self.contentView addSubview:self.indicator];

    }
    return self;
}

// zoomRect
- (void)animateScaleImage{
    if (self.scaleView.zoomScale > 1.0) {
        [self.scaleView setZoomScale:1.0 animated:YES];
    }else{
        [self.scaleView setZoomScale: 2.0 animated:YES];
    }
}

- (void)layoutSubviews{
    [super layoutSubviews];
    if (self.imageView.image == nil) {
        self.imageView.frame = self.contentView.bounds;
    }else{
        self.imageView.frame = self.bounds;
    }
    
}

#pragma mark - UIScrollViewDelegate
- (nullable UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView{
    return self.imageView;
}

- (void)setImagURL:(NSString *)url complete:(dispatch_block_t)complete{
    if (complete) {
        complete();
    }
}


@end


